package com.gxa.shop.dao.brand.impl;

import com.gxa.shop.bean.dto.BrandQueryPage;
import com.gxa.shop.bean.pojo.Brand;
import com.gxa.shop.bean.pojo.Category;
import com.gxa.shop.bean.vo.BrandOption;
import com.gxa.shop.commons.jdbc.JDBCUtil;
import com.gxa.shop.dao.brand.BrandDao;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * com.gxa.shop.bean.dao.impl
 * User: zjy
 * Date: 2024/12/18 9:54
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
public class BrandDaoImpl implements BrandDao {
    @Override
    public Category queryById(Integer brandId) {
        return null;
    }

    @Override
    public int insert(Brand brand) {
        String  sql="insert  brand (brand_name,brand_image) value (?,?)";
        JDBCUtil jdbcUtil=new JDBCUtil();
        int update = jdbcUtil.update(sql,
                brand.getBrandName(),
                brand.getBrandImage());
        return update;
    }

    @Override
    public int update(Brand brand) {
        String  sql="update brand set  brand_name=?,brand_image=? where  brand_id=?";
        JDBCUtil  jdbcUtil=new JDBCUtil();
        int update = jdbcUtil.update(sql, brand.getBrandName(),brand.getBrandImage(),brand.getBrandId());
        return update;
    }

    @Override
    public int deleteById(Integer brandId) {
        String deleteProductsSQL = "DELETE FROM shop.product WHERE brand_id = ?";
        String deleteBrandSQL = "DELETE FROM shop.brand WHERE brand_id = ?";

        JDBCUtil jdbcUtil = new JDBCUtil();

        try {
            // 开始事务
            jdbcUtil.beginTransaction();

            // 删除所有依赖于该品牌的商品
            int productsDeleted = jdbcUtil.update(jdbcUtil.getConnection(), deleteProductsSQL, brandId);

            // 删除品牌本身
            int brandsDeleted = jdbcUtil.update(jdbcUtil.getConnection(), deleteBrandSQL, brandId);

            // 提交事务
            jdbcUtil.endTransaction(true);

            // 返回受影响的行数（可以是产品或品牌的数量）
            return productsDeleted + brandsDeleted;

        } catch (Exception e) {
            // 如果发生异常，则回滚事务
            jdbcUtil.endTransaction(false);
            throw new RuntimeException("删除品牌及其关联商品时发生错误", e);
        } finally {
            jdbcUtil.close(); // 关闭资源
        }
    }

    @Override
    public String getBrandImageByBrandId(String brandId) {
        String imagePath = null;

        // SQL 查询语句
        String sql = "SELECT brand_image FROM brand WHERE brand_id = ?";

        // 使用 JDBCUtil 获取数据库连接并执行查询
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> result = jdbcUtil.query(sql, brandId);

        // 检查结果集并提取图片路径
        if (!result.isEmpty()) {
            Map<String, Object> row = result.get(0); // 假设brand_id是唯一的，只取第一个结果
            imagePath = (String) row.get("brand_image");
        }

        // 返回图片路径
        return imagePath;
    }


    @Override
    public void updateBrandImage(String brandId, String imagePath) {
        String sql = "UPDATE brand SET brand_image = ?,brand_name=? WHERE brand_id = ?";

        // 使用 JDBCUtil 执行更新操作
        JDBCUtil jdbcUtil = new JDBCUtil();
        int resultRows = jdbcUtil.update(sql, imagePath, brandId);

        // 检查更新结果（可选）
        if (resultRows > 0) {
            System.out.println("图片路径更新成功！");
        } else {
            System.out.println("没有找到对应的品牌ID，更新失败！");
        }
    }


    @Override
    public Long findByTotal(BrandQueryPage brandQueryPage) {
        StringBuffer sql = new StringBuffer("select count(*) as ct from brand where 1=1");
        List<Object> parameters = new ArrayList<>();
        System.out.println("brandName: '" + brandQueryPage.getBrandName() + "'");

        // 验证是否为空  null  "    "
        if (brandQueryPage.getBrandName() != null && !brandQueryPage.getBrandName().trim().isEmpty()) {
            parameters.add(brandQueryPage.getBrandName());
            sql.append(" and brand_name like concat('%', ?, '%')");
        }
        System.out.println("sql: " + sql);
        System.out.println("参数: " + parameters);

        JDBCUtil jdbcUtil = new JDBCUtil();
        try {
            List<Map<String, Object>> query = jdbcUtil.query(sql.toString(), parameters.toArray());
            Long ct = 0L;
            if (query.size() > 0) {
                ct = (Long) query.get(0).get("ct");
            }
            return ct;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询分类总数时发生错误: " + e.getMessage());
            return 0L;
        }
    }

    @Override
    public List<Brand> findByPage(BrandQueryPage brandQueryPage) {
        StringBuffer sql=new StringBuffer("select brand_id,brand_name,brand_image from brand where 1=1");
        List<Object>  parameters=new ArrayList<>();
        if(brandQueryPage.getBrandName()!=null){
            parameters.add(brandQueryPage.getBrandName());
            sql.append(" and  brand_name like  concat('%',?,'%')");
        }
        sql.append("  order by brand_id  asc");
        sql.append("  limit  "+((brandQueryPage.getPage()-1)*brandQueryPage.getLimit())
                +","+brandQueryPage.getLimit());
        System.out.println("sql:"+sql);
        System.out.println("参数:"+parameters);
        JDBCUtil jdbcUtil=new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql.toString(), parameters.toArray());
        if(query.size()>0){
            List<Brand> list=new ArrayList<>();
            for (Map<String, Object> row : query) {//Community
                Brand  brand=new Brand();
                brand.setBrandId((Integer) row.get("brand_id"));
                brand.setBrandName((String) row.get("brand_name"));
                brand.setBrandImage((String) row.get("brand_image"));
                list.add(brand);
            }
            return  list;
        }

        return null;
    }

    @Override
    public List<BrandOption> findAllList() {
        String sql="select brand_id,brand_name from brand";
        JDBCUtil jdbcUtil=new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql);
        if(query.size()>0){
            List<BrandOption> list=new ArrayList<>();
            for (Map<String, Object> row : query) {
                BrandOption  brandOption=new BrandOption();
                brandOption.setBrandId((Integer) row.get("brand_id"));
                brandOption.setBrandName((String) row.get("brand_name"));
                list.add(brandOption);
            }
            return  list;
        }
        return null;
    }
}